#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2021/3/11 19:51
# @Author  : cjw
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from os.path import exists, basename, join
from smtplib import SMTP_SSL
from setting.setting import *


class Email:

	def __init__(self,
	             title: str,
	             receiver: [str, list],
	             sender: tuple = MAIL_USERNAME,
	             server: str = MAIL_SERVER,
	             auth_code: str = MAIL_PASSWORD,
	             port: int = MAIL_PORT,
	             message: str = None,
	             attachment_file: [str, list] = None):
		"""
		:param title:邮件主题
		:param receiver:收件人
		:param sender: 发件人
		:param server:发件人邮箱服务器
		:param auth_code:登录授权码
		:param port:登录端口
		:param message:邮件正文
		:param attachment_file:附件
		"""
		self.sender = sender
		self.receiver = receiver
		self.title = title
		self.message = message
		self.attachment_file = attachment_file
		self.server = server
		self.auth_code = auth_code
		self.port = port
		self.msg = MIMEMultipart('related')

	def send(self):
		self.msg['Subject'] = self.title
		self.msg['From'] = formataddr(pair=self.sender)
		self.msg['To'] = self.receiver
		if self.message:
			self.msg.attach(MIMEText(self.message, _charset='utf-8'))
		if self.attachment_file:
			if isinstance(self.attachment_file, str):
				self._attach_file(self.attachment_file)
			elif isinstance(self.attachment_file, list):
				for _path in self.attachment_file:
					self._attach_file(_path)
		# 登录邮箱，发送邮件
		smtp_server = SMTP_SSL(self.server, self.port)
		smtp_server.login(self.sender[1], self.auth_code)
		try:
			smtp_server.sendmail(self.sender[1], self.receiver, self.msg.as_string())
		except Exception as e:
			raise e
		finally:
			smtp_server.quit()

	def _attach_file(self, file_path):
		"""
		附件文件绑定
		:param file_path: 文件路径
		:return:
		"""
		if not exists(file_path):
			raise FileNotFoundError(f'附件文件不存在或者路径错误: {file_path}')
		with open(file_path, 'r', encoding='utf-8') as f:
			attach_file = MIMEText(f.read(), 'plain', 'utf-8')
		attach_file['Content-Type'] = 'application/octet-stream'
		file_name = basename(file_path)
		attach_file['Content-Disposition'] = f'attachment;filename="{file_name}"'
		self.msg.attach(attach_file)


if __name__ == '__main__':
	email = Email(title='测试邮件发送标题',
	              receiver='18367157420@163.com',
	              message='测试邮件发送内容',
	              attachment_file=join(BASE_PATH, 'report.html'))
	email.send()
